package biolabs.util;

import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.NoSuchElementException;

public class ConcatenatingIterable<E> implements Iterable<E> {

	private final List<Iterable<? extends E>> iterables;
	
	private class ConcatenatingIterator implements Iterator<E> {
		private final Iterator<Iterable<? extends E>> collIter;
		private Iterator<? extends E> elemIter;
		
		public ConcatenatingIterator() {
			this.collIter = iterables.iterator();
			this.elemIter = new Iterator<E>(){

				@Override
				public boolean hasNext() {
					return false;
				}

				@Override
				public E next() {
					throw new NoSuchElementException();
				}

				@Override
				public void remove() {
					throw new UnsupportedOperationException();
				}
				
			};
		}

		@Override
		public boolean hasNext() {
			while( !elemIter.hasNext() ){
				if( !collIter.hasNext() )
					return false;
				elemIter = collIter.next().iterator();
			}
			return true;
		}

		@Override
		public E next() {
			if(hasNext())
				return elemIter.next();
			else
				throw new NoSuchElementException();
		}

		@Override
		public void remove() {
			throw new UnsupportedOperationException();
		}
	}


	public ConcatenatingIterable(Collection<? extends Iterable<? extends E>> coll){
		iterables = new LinkedList<Iterable<? extends E>>(coll);
	}

	@Override
	public Iterator<E> iterator() {
		return new ConcatenatingIterator();
	}

}
